package com.the_last.service.impl;

import com.the_last.mapper.UserMapper;
import com.the_last.pojo.bo.LoginUser;
import com.the_last.pojo.vo.UserWithPermissionList;
import com.the_last.utils.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserDetailsImpl implements UserDetailsService {
    
    @Resource
    private final UserMapper userMapper;
    
    public UserDetailsImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || username.trim().isEmpty()) {
            log.warn("用户名不能为空");
            throw new UsernameNotFoundException("用户名不能为空");
        }
        
        try {
            // 查询用户信息和权限列表（多行结果）
            UserWithPermissionList userWithPermissionList = userMapper.selectUserWithPermission(username);
            
            if (Objects.isNull(userWithPermissionList)) {
                log.warn("用户登录失败，用户不存在或已禁用: {}", username);
                throw new InternalAuthenticationServiceException("用户不存在或已禁用");
            }
            
            userWithPermissionList.getUser().setId(userWithPermissionList.getUserId());
            List<String> permissionList = userWithPermissionList.getPermissionList();
            
            LoginUser loginUser = new LoginUser(userWithPermissionList.getUser(), permissionList);
            
            log.debug("用户 {} 加载成功，权限数量: {}", username, permissionList.size());
            return loginUser;
            
        } catch (Exception e) {
            log.error("加载用户信息失败，username: {}", username, e);
            throw new InternalAuthenticationServiceException("用户认证失败");
        }
    }
}